package cn.com.open.itembank.service.impl;

import cn.com.open.itembank.common.*;
import cn.com.open.itembank.common.enums.HaulType;
import cn.com.open.itembank.common.enums.Source;
import cn.com.open.itembank.common.enums.SysState;
import cn.com.open.itembank.controller.ChapterController;
import cn.com.open.itembank.dto.*;
import cn.com.open.itembank.entity.Chapter;
import cn.com.open.itembank.entity.CourseItemBank;
import cn.com.open.itembank.mapper.ChapterMapper;
import cn.com.open.itembank.service.ChapterService;
import cn.com.open.itembank.service.ItemBankService;
import cn.com.open.itembank.utils.DateUtil;
import cn.com.open.itembank.utils.ListUtil;
import cn.com.open.itembank.utils.UUIDUtil;
import cn.com.open.itembank.utils.StringUtil;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;

/**
 * Created by lucky on 2017/7/17.
 */
@Service("chapterService")
public class ChapterServiceImpl implements ChapterService {
    private static org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(ChapterController.class);

    @Autowired
    private ChapterMapper mapper;

    @Value("${app.resource.api.url}")
    private String resource;

    @Autowired
    private ItemBankService itemBankService;

    private String parentId = "00000000-0000-0000-0000-000000000000";
    //region 获取指定章节信息

    /**
     * 根据章节id获取章节信息.
     *
     * @param id 章节id
     * @return 章节信息
     */
    @Override
    public Chapter getChapterById(String id) {
        if (!UUIDUtil.isUUID(id)) {
            return null;
        }
        return mapper.getById(id);

    }


    //endregion

    //region 各类存在判断

    /**
     * 根据题库ID，父节点ID和章节名称判断是否存在重名章节.
     *
     * @param itemBankId 题库ID
     * @param pid        父节点ID
     * @param name       章节名称
     * @return 0，不存在；其他，存在；
     */
    private int isExistSameNameInParent(String itemBankId, String pid, String name) {
        if (!UUIDUtil.isUUID(itemBankId) || !UUIDUtil.isUUID(pid)) {
            return GlobalConst.DATA_FORMAT_ERROR;
        }

        int count = mapper.getCountByPidAndName(itemBankId, pid, name);
        if (count == 0) {
            return GlobalConst.SUCCESS;
        }
        return GlobalConst.DATA_EXIST;
    }

    /**
     * 修改时是否重名
     *
     * @param itemBankId  题库ID
     * @param id          章节id
     * @param pid         父章节id
     * @param chapterName 章节名称
     * @return 0，不存在；其他，存在；
     */
    private int isExistChapter(String itemBankId, String id, String pid, String chapterName) {
        if (!UUIDUtil.isUUID(itemBankId) || !UUIDUtil.isUUID(pid)) {
            return GlobalConst.DATA_FORMAT_ERROR;
        }

        int count = mapper.isExistChapter(itemBankId, id, pid, chapterName);

        if (count == 0) {
            return GlobalConst.SUCCESS;
        }
        return GlobalConst.DATA_EXIST;
    }
    //endregion

    //region 新增章节

    /**
     * 新增章节.
     *
     * @param chapter 章节信息
     * @return the int
     */
    @Override
    public ReturnModel insert(String itemBankId, Chapter chapter) {
        ReturnModel model = new ReturnModel();
        if (!UUIDUtil.isUUID(chapter.getCourseID()) || !UUIDUtil.isUUID(chapter.getParentChapterID()) || StringUtil.isEmpty(chapter.getChapterName())) {
            model.setCode(GlobalConst.INCOMPLETE_DATA);
            return model;
        }

        //判断该课程题库，是否来源于内部
        if (!itemBankService.isInnerCourse(chapter.getCourseID())) {
            model.setCode(GlobalConst.OTHER_ERROR);
            return model;
        }

        //添加时判断是否重名
        int result = isExistSameNameInParent(chapter.getCourseID(), chapter.getParentChapterID(), chapter.getChapterName());
        if (result != GlobalConst.SUCCESS) {
            model.setCode(result);
            return model;
        }

        int order = mapper.getMaxOrdersByPid(chapter.getParentChapterID());

        order++;

        try {
            Chapter chap = new Chapter();

            chap.setChapterID(UUID.randomUUID().toString());
            chap.setParentChapterID(chapter.getParentChapterID());
            chap.setChapterName(chapter.getChapterName());
            chap.setCreateTime(DateUtil.getCurrentTimeToShowString());
            chap.setChapterType(chapter.getChapterType());
            chap.setComment("");
            chap.setCourseID(chapter.getCourseID());
            chap.setCreater(GlobalConst.EMPTYUUID);
            chap.setDepth(chapter.getDepth());
            chap.setOrders(order);
            chap.setStatus(SysState.START.getIndex());

            mapper.insert(chap);
            model.setCode(GlobalConst.SUCCESS);
            model.setData(chap.getChapterID());
            return model;
        } catch (Exception e) {
            model.setCode(GlobalConst.DATA_BASE_ERROR);
            return model;
        }
    }
    //endregion

    //region 修改章节

    /**
     * 修改章节名称.
     *
     * @param id          章节id
     * @param chapterName 章节名称
     * @return the int
     */
    @Override
    public ReturnModel updateChapterName(String appKey, String itembankId, String id, String chapterName) {
        ReturnModel model = basicCheck(appKey, itembankId, id);
        if (model.getCode() != GlobalConst.SUCCESS) {
            return model;
        }
        Chapter chapter = (Chapter) model.getData();

        //修改时是否重名
        int result = isExistChapter(chapter.getCourseID(), id, chapter.getParentChapterID(), chapterName);
        if (result != GlobalConst.SUCCESS) {
            model.setCode(result);
            return model;
        }

        try {
            mapper.update(id, chapterName);
            model.setCode(GlobalConst.SUCCESS);
            return model;
        } catch (Exception e) {
            model.setCode(GlobalConst.DATA_BASE_ERROR);
            return model;
        }
    }

    /**
     * 拖拽更新章节
     *
     * @param chapterId 章节ID
     * @param parentId  父章节ID
     * @param type      拖拽类型
     * @return
     */
    @Override
    public ReturnModel updateChapter(String appKey, String itemBankId, String chapterId, String parentId, Integer type) {

        //检测的私有方法
        ReturnModel model = basicCheck(appKey, itemBankId, chapterId);

        if (model.getCode() != GlobalConst.SUCCESS) {
            return model;
        }
        Chapter chapter = (Chapter) model.getData();
        //拖拽本层节点
        if (type == HaulType.inner.getIndex()) {
            Chapter newChapter = new Chapter();
            newChapter.setChapterID(chapterId);
            newChapter.setParentChapterID(parentId);
            newChapter.setChapterName(chapter.getChapterName());
            newChapter.setCreateTime(chapter.getCreateTime());
            newChapter.setChapterType(0);
            newChapter.setComment("");
            newChapter.setCourseID(chapter.getCourseID());
            newChapter.setCreater(UUID.randomUUID().toString());
            newChapter.setOrders(0);
            newChapter.setStatus(1);
            mapper.updateChapter(newChapter);
            model.setCode(GlobalConst.SUCCESS);
            model.setMessage("修改节点成功");
        }
        //章节移动到目标上
        if (type == HaulType.prev.getIndex()) {
           drag(chapterId,parentId,chapter);
        }
        //章节移动到目标下
        if (type == HaulType.down.getIndex()) {
            drag(chapterId,parentId,chapter);
        }
        return model;
    }

    /**
     * 上下拖拽
     * @param chapterId
     * @param parentId
     * @param chapter
     * @return
     */
    private ReturnModel drag(String chapterId, String parentId,Chapter chapter) {
        ReturnModel model = new ReturnModel();
        Chapter chapter1 = mapper.getChapterByIdAndPid(chapterId, parentId);
        Chapter chapter2 = mapper.getChapterByIdAndDepth(chapter1.getDepth());
        for (int i = chapter1.getOrders(); i < chapter2.getOrders(); i++) {
            Chapter chapter3 = mapper.getChapter(i, chapter1.getDepth(), chapter1.getParentChapterID());
            chapter3.setOrders(chapter3.getOrders() + 1);
            mapper.updateChapter(chapter3);
        }
        Chapter chapter4 = mapper.getById(parentId);
        if (chapter4.getParentChapterID() == null) {
            model.setCode(GlobalConst.ID_NOT_EXIST);
            model.setMessage("父节点不存在");
            return model;
        }
        Chapter newChapter = new Chapter();
        newChapter.setChapterID(chapterId);
        newChapter.setParentChapterID(chapter4.getParentChapterID());
        newChapter.setChapterName(chapter.getChapterName());
        newChapter.setCreateTime(chapter.getCreateTime());
        newChapter.setChapterType(0);
        newChapter.setComment("");
        newChapter.setCourseID(chapter.getCourseID());
        newChapter.setCreater(UUID.randomUUID().toString());
        newChapter.setOrders(chapter1.getOrders() + 1);
        newChapter.setStatus(1);
        mapper.updateChapter(newChapter);
        model.setCode(GlobalConst.SUCCESS);
        model.setMessage("修改节点成功");
        return model;
    }
    /**
     *
     */

    /**
     * 拖拽数据同步
     *
     * @param chapterInputModel model
     * @return
     */
    @Override
    public ReturnModel dragChapter(String appKey, String itemBankId, ChapterInputModel chapterInputModel) {

        //检测的私有方法
        ReturnModel model = basicCheck(appKey, itemBankId, null);

        if (model.getCode() != GlobalConst.SUCCESS) {
            return model;
        }
        if (chapterInputModel == null) {
            model.setCode(GlobalConst.DATA_FORMAT_ERROR);
            model.setMessage("数据不完整");
            return model;
        }
        List<ChapterModel> items = chapterInputModel.getItems();
        recursionUpdate(items, parentId, 0);
        model.setCode(GlobalConst.SUCCESS);
        model.setMessage("同步数据库成功");
        return model;
    }

    /**
     * 同步数据库
     *
     * @param items
     * @param parentId
     * @param depth
     */
    private void recursionUpdate(List<ChapterModel> items, String parentId, int depth) {
        for (int i = 0; i < items.size(); i++) {
            Chapter chapter = mapper.getById(items.get(i).getChapterID());
            if (chapter != null) {
                chapter.setParentChapterID(parentId);
                chapter.setOrders(i);
                chapter.setDepth(depth);
                mapper.updateChapter(chapter);
                if (items.get(i).getChildren() != null || !StringUtil.isEmpty(items.get(i).getChildren().toString())) {
                    recursionUpdate(items.get(i).getChildren(), items.get(i).getChapterID(), depth + 1);
                }
            }
        }
    }
    //endregion

    //region 删除章节

    /**
     * 删除题库下全部章节信息.
     *
     * @param itemBankId 题库ID
     * @return the int
     */
    @Override
    public ReturnModel deleteByItemBankId(String itemBankId) {
        ReturnModel model = new ReturnModel();
        if (!UUIDUtil.isUUID(itemBankId)) {
            model.setCode(GlobalConst.DATA_FORMAT_ERROR);
            return model;
        }
        List<Chapter> chapterList = mapper.getChapterListByItemBnakId(itemBankId);
        if (chapterList != null) {
            for (Chapter chapter : chapterList) {
                mapper.deleteByItemBankId(chapter.getChapterID());
            }
        }
        model.setCode(GlobalConst.SUCCESS);
        return model;
    }

    /**
     * 根据章节ID删除章节.
     *
     * @param chapterId 题库ID
     * @return the int
     */
    @Override
    public ReturnModel deleteById(String appKey, String itemBankId, String chapterId) {
        //检测的私有方法
        ReturnModel model = basicCheck(appKey, itemBankId, chapterId);
        //判断题库id是否存在，章节id是否存在。
        if (model.getCode() != GlobalConst.SUCCESS) {
            return model;
        }
        //得到本章节
        Chapter chapter = (Chapter) model.getData();
        //根据章节得到本章节得courseId，通过courseID获取本课程下得所有章节集合
        Chapter chap = (Chapter) model.getData();
        List<ChapterModel> allList = getChapterList(chap.getCourseID());
        //获取章节的子孙节点
        for (ChapterModel chapterModel : allList) {
            if (chap.getChapterID().equalsIgnoreCase(chapterModel.getChapterID())) {
                //递归调用（获取章节的子节点）
                List<String> c = findChapterChildren(allList, chapterModel.getChapterID());
                c.add(chap.getChapterID());
                //删除每一个章节（要判断是否和试题关联）
                for (String chapId : c) {
                    if (mapper.getQuestionChapterInfo(chapId) > 0) {
                        model.setCode(GlobalConst.DATA_EXIST);
                        model.setMessage("此章节已经被试题使用，无法删除");
                        return model;
                    }
                    mapper.deleteById(chapId);
                }
            }
        }
        //排序
        // 查询与删除章节同一级别的章节（排序用）
        List<Chapter> parentChapterList = mapper.getParentChapter(chapter.getParentChapterID());
        if (parentChapterList != null) {
            for (Chapter chapter1 : parentChapterList) {
                mapper.updateChapterOrder(chapter1.getChapterID());
            }
        }
        model.setCode(GlobalConst.SUCCESS);
        return model;
    }

    /**
     * 递归查找章节子级
     *
     * @param parentList
     */
    private List<String> findChapterChildren(List<ChapterModel> parentList, String pid) {
        List<String> list = new ArrayList<>();
        for (ChapterModel chapterModel : parentList) {
            if (chapterModel.getParentID().equalsIgnoreCase(pid)) {
                //查询本章节下所有得子章节
                List<String> c = findChapterChildren(parentList, chapterModel.getChapterID());
                list.add(chapterModel.getChapterID());
                list.addAll(c);
            }
        }
        return list;
    }

    /**
     * 根据题库Id获取章节集合
     *
     * @param courseID
     * @return
     */
    private List<ChapterModel> getChapterList(String courseID) {
        List<ChapterModel> chapterModelList = new ArrayList<>();
        List<Chapter> chapterList = mapper.getChapterListByItemBnakId(courseID);
        if (chapterList != null) {
            for (int i = 0; i < chapterList.size(); i++) {
                ChapterModel model = new ChapterModel();
                model.setChapterID(chapterList.get(i).getChapterID() == null ? "" : chapterList.get(i).getChapterID());
                model.setLevel(chapterList.get(i).getDepth() == null ? 0 : chapterList.get(i).getDepth());
                model.setName(chapterList.get(i).getChapterName() == null ? "" : chapterList.get(i).getChapterName());
                model.setType(chapterList.get(i).getChapterType() == null ? 0 : chapterList.get(i).getChapterType());
                model.setParentID(chapterList.get(i).getParentChapterID() == null ? "" : chapterList.get(i).getParentChapterID());
                model.setSort(chapterList.get(i).getOrders() == null ? 0 : chapterList.get(i).getOrders());
                chapterModelList.add(model);
            }
        }
        return chapterModelList;
    }


    /**
     * 根据子章节ID和父章节ID删除章节信息
     *
     * @param childIds  子章节ID集合
     * @param chapterId 章节ID
     * @return
     */
    @Override
    public ReturnModel deleteByChildId(String appKey, String itemBankId, String childIds, String chapterId) {
        //检测的私有方法
        ReturnModel model = basicCheck(appKey, itemBankId, chapterId);

        if (model.getCode() != GlobalConst.SUCCESS) {
            return model;
        }
        Chapter chapter = (Chapter) model.getData();
        List<Chapter> chapterList = mapper.getDepthById(chapter.getDepth());
        if (chapterList.size() != 1) {
            //需要删除子章节
            Chapter chapterDepth = mapper.getChapterByIdAndDepth(chapter.getDepth());
            if (chapterDepth.getOrders() != chapter.getOrders()) {
                for (int i = chapter.getOrders() + 1; i <= chapterDepth.getOrders(); i++) {
                    Chapter chapterByOrderAndDepth = mapper.getChapterByOrderAndDepth(i, chapter.getDepth());
                    if (chapterByOrderAndDepth != null) {
                        chapterByOrderAndDepth.setOrders(chapterByOrderAndDepth.getOrders() - 1);
                        mapper.updateChapter(chapterByOrderAndDepth);
                    }

                }
            }
        }
        String[] childId = childIds.split(",");
        for (int i = 0; i < childId.length; i++) {
            mapper.deleteById(childId[i]);
        }
        model.setCode(GlobalConst.SUCCESS);
        model.setMessage("删除成功");
        return model;
    }


    //endregion

    //region  获取章节

    /**
     * 获取课程全部章节
     *
     * @param itemBankId
     * @return
     */
    @Override
    public ReturnModel getCourseChapter(String appKey, String itemBankId) {
        ReturnModel model = new ReturnModel();
        CourseItemBank courseItemBank = mapper.getCourseItemBank(itemBankId);
        if (courseItemBank == null) {
            model.setCode(GlobalConst.ID_NOT_EXIST);
            model.setMessage("课程id不存在");
            return model;
        }
        if (courseItemBank.getSource() == Source.OUTER.getIndex()) {
            return null;
        }
        List<Chapter> chaptList = mapper.getChapterByOrder(itemBankId);
        List<Chapter> chapters = new ArrayList<>();
        for (Chapter chapter : chaptList) {
            chapters.add(dataToModel(chapter));
        }
        ChapterListModel rootChapterList = getRootChapter(chapters);
        model.setCode(GlobalConst.SUCCESS);
        model.setData(rootChapterList);
        return model;
    }

    /**
     * 获取章节列表
     *
     * @param itemBankId 题库id
     * @return
     */
    @Override
    public ReturnModel getChapterList(String appKey, String itemBankId) {
        ReturnModel model = checkItemBank(itemBankId);
        if (model.getCode() != GlobalConst.SUCCESS) {
            return model;
        }
        List<Chapter> chapterList = mapper.getChapterListByItemBnakId(itemBankId);
        int count = mapper.getChapterCount();
        JSONObject json = new JSONObject();
        json.put("count", count);
        json.put("list", chapterList);

        model.setData(json);
        return model;
    }

    /**
     * 获取课程题库下所有章节列表(树)
     *
     * @param itemBankId
     * @return
     */
    @Override
    public ReturnModel getAllChaptList(String appKey, String itemBankId) {
        ReturnModel model = basicCheck(appKey, itemBankId, null);
        if (model.getCode() != GlobalConst.SUCCESS) {
            return model;
        }
        //得到所有的章节
        List<Chapter> chapterListByItemBnakId = mapper.getChapterListByItemBnakId(itemBankId);
        List<ZTreeModel> zTreeModelList = getZTreeModel(chapterListByItemBnakId);
        model.setData(zTreeModelList);
        return model;
    }

    /**
     * 获取章节（策略用）
     *
     * @param itemBankId     题库id
     * @param firstChapterId 第一个章节id
     * @param lastChapterId  最后一个章节id
     * @return
     */
    @Override
    public ReturnModel getChaptForRules(String appKey, String itemBankId, String firstChapterId, String lastChapterId) {
        ReturnModel model = basicCheck(appKey, itemBankId, null);
        if (model.getCode() != GlobalConst.SUCCESS) {
            return model;
        }
        // 如果章节ID为空则获取课程下全部数据
        if (mapper.getById(lastChapterId) == null) {
            ReturnModel allChaptList = getAllChaptList(appKey, itemBankId);
            model.setData(allChaptList);
            return model;
        } else {
            Chapter firstChapter = mapper.getById(firstChapterId);
            Chapter lastChapter = mapper.getById(lastChapterId);
            if (lastChapter.getOrders() > firstChapter.getOrders()) {
                int temp = lastChapter.getOrders();
                lastChapter.setOrders(firstChapter.getOrders());
                firstChapter.setOrders(temp);
            }
            List<ZTreeModel> zTreeModelList = new ArrayList<>();
            for (int i = 0; i < lastChapter.getOrders(); i++) {
                List<Chapter> cList = mapper.getChaptcerList(lastChapter.getChapterID(),
                        lastChapter.getCourseID(), lastChapter.getDepth(), lastChapter.getOrders(), i);
                for (Chapter chapter : cList) {
                    ZTreeModel zTreeModel = insertChapter(chapter);
                    zTreeModel.getChildren().addAll(getChildByxDep(zTreeModel, itemBankId));
                    zTreeModelList.add(zTreeModel);
                }

            }
            model.setData(zTreeModelList);
            return model;
        }
    }

    /**
     * 获取章节（策略修改用）
     *
     * @param itemBankId
     * @param chapterId
     * @return
     */
    @Override
    public ReturnModel getChaptForUpdateRules(String appKey, String itemBankId, String chapterId) {
        //检测的私有方法
        ReturnModel model = basicCheck(appKey, itemBankId, chapterId);

        if (model.getCode() != GlobalConst.SUCCESS) {
            return model;
        }
        ReturnModel allChaptList = getAllChaptList(appKey, itemBankId);
        model.setData(allChaptList);
        return model;
    }

    /**
     * 获取章节(根据章节集合和章节id串)
     *
     * @param chapterList
     * @param chapterId
     * @return
     */
    @Override
    public ReturnModel getChildModel(String appKey, String itemBankId, List<Chapter> chapterList, String chapterId) {
        //检测的私有方法
        ReturnModel model = basicCheck(appKey, itemBankId, chapterId);

        if (model.getCode() != GlobalConst.SUCCESS) {
            return model;
        }
        List<Chapter> chapterByChapterList = mapper.getChapterByChapterList(chapterId);
        List<Chapter> chapters = new ArrayList<>();
        if (chapterByChapterList!=null) {
            for (int i = 0; i < chapterByChapterList.size(); i++) {
                chapters.add(dataToModel(chapterByChapterList.get(i)));
            }
            chapterList.addAll(chapters);
            for (int j = 0; j < chapters.size(); j++) {
                getChildModel(appKey, itemBankId, chapterList, String.join(",", chapters.get(j).getChapterID()));
            }
        }
        model.setData(chapterList);
        return model;
    }

    /**
     * 根据课程Id获取章节（外部课程）
     *
     * @param courseId
     * @return
     */
    @Override
    public ReturnModel getChapterByCourseId(String appKey, String courseId) {

        //检测的私有方法
        ReturnModel model = basicCheck(appKey, courseId, null);

        if (model.getCode() != GlobalConst.SUCCESS) {
            return model;
        }
        String timeStamp = DateUtil.toLongString(new Date());
        String urlString = resource + "courses/" + courseId + "/catalogTree?timestamp=" + timeStamp;
        StringBuilder result = new StringBuilder();
        try {
            URL url = new URL(urlString);

            URLConnection conn = url.openConnection();
            //设置超时间为3秒
            conn.setConnectTimeout(3 * 1000);
            //防止屏蔽程序抓取而返回403错误
            conn.setRequestProperty("Charset", "utf-8");
            conn.setRequestProperty("appkey", "c655762fdf5979cb382c94061d6ddebb");
            conn.setRequestProperty("appsecret", "a92831a56f957a98e2ebe10caff37f86");
            InputStream input = conn.getInputStream();
            int ss;
            while ((ss = input.read()) != -1) {
                result.append((char) ss);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        model.setData(result.toString());
        return model;
    }
    //endregion

    //region  私有方法

    /**
     * 递归调用(获取章节列表用)
     *
     * @param list
     * @return
     */
    private List<ZTreeModel> getZTreeModel(List<Chapter> list) {
        List<ZTreeModel> result = new ArrayList<>();

        if (list != null) {
            for (Chapter chapter : list) {
                if (chapter.getParentChapterID().equalsIgnoreCase(parentId)) {
                    //实例化树根节点
                    ZTreeModel model = insertChapter(chapter);
                    //获取子孙节点集合
                    List<ZTreeModel> childChapterList = getChildChapterList(list, chapter.getChapterID());
                    if (!ListUtil.isNullOrEmpty(childChapterList)) {
                        model.getChildren().addAll(childChapterList);
                    }
                    result.add(model);
                }
            }
        }
        return result;
    }

    /**
     * 模型对应填值
     *
     * @param chapter
     */
    private ZTreeModel insertChapter(Chapter chapter) {
        ZTreeModel zTreeModel = new ZTreeModel();
        zTreeModel.setIcon(chapter.getChapterType().toString());
        zTreeModel.setChildOuter(false);
        zTreeModel.setType(chapter.getChapterType());
        zTreeModel.setId(chapter.getChapterID());
        zTreeModel.setName(chapter.getChapterName());
        zTreeModel.setPid(chapter.getParentChapterID());
        zTreeModel.setDepth(chapter.getDepth());
        zTreeModel.setOrders(chapter.getOrders());
        zTreeModel.setChildren(new ArrayList<>());
        return zTreeModel;
    }

    /**
     * 得到每一层对应的节点
     *
     * @param list
     * @param pId
     * @return
     */
    private List<ZTreeModel> getChildChapterList(List<Chapter> list, String pId) {
        List<ZTreeModel> result = new ArrayList<>();
        //得到所有的章节，找到所属的节点
        for (Chapter chapter : list) {
            if (chapter.getParentChapterID().equalsIgnoreCase(pId)) {
                //实例化树根节点
                ZTreeModel model = insertChapter(chapter);

                List<ZTreeModel> childChapterList = getChildChapterList(list, chapter.getChapterID());
                if (!ListUtil.isNullOrEmpty(childChapterList)) {
                    model.getChildren().addAll(childChapterList);
                }

                result.add(model);
            }
        }
        return result;
    }

    /**
     * 递归调用（策略用）
     *
     * @param zTreeModel
     * @param itemBankId
     * @return
     */
    private List<ZTreeModel> getChildByxDep(ZTreeModel zTreeModel, String itemBankId) {
        List<Chapter> chapterList = mapper.getChapterListByItemBnakId(itemBankId);
        List<ZTreeModel> list = new ArrayList<>();
        for (Chapter chapter : chapterList) {
            if (chapter.getChapterID().toLowerCase() == zTreeModel.getId().toLowerCase()) {
                ZTreeModel model = insertChapter(chapter);
                model.getChildren().addAll(getChildByxDep(model, itemBankId));
                list.add(model);
            }
        }
        return list;
    }

    /**
     * 获取课程全部章节（递归）
     *
     * @param chapters
     */
    private ChapterListModel getRootChapter(List<Chapter> chapters) {
        //查询第一条
        Chapter chapters1 = mapper.getChapterListByParentId(parentId);
        ChapterListModel chapterListMode = new ChapterListModel();
        for (Chapter chapter : chapters) {
            if (chapter.getParentChapterID() == chapters1.getChapterID()) {
                List<ChapterListModel> chiledList = getChildChapter(chapters, chapters1.getChapterID());
                chapterListMode.getChiledren().addAll(chiledList);
            }
        }
        return chapterListMode;
    }

    /**
     * 递归调用获取课程下所有章节
     *
     * @param chapters
     * @param parentId
     * @return
     */
    private List<ChapterListModel> getChildChapter(List<Chapter> chapters, String parentId) {
        List<ChapterListModel> modelList = new ArrayList<>();
        List<Chapter> chaptersList = mapper.getChapterListByParentIdOrder(parentId);
        for (Chapter chapter : chaptersList) {
            ChapterListModel model = new ChapterListModel();
            for (Chapter chapter1 : chapters) {
                if (chapter1.getParentChapterID() == chapter.getChapterID()) {
                    List<ChapterListModel> childList = getChildChapter(chaptersList, chapter.getCourseID());
                    model.getChiledren().addAll(childList);
                }
                modelList.add(model);
            }
        }
        return modelList;
    }

    /**
     * 获取获取课程全部章节（创建实体）
     *
     * @param chapter
     * @return
     */
    private Chapter dataToModel(Chapter chapter) {
        Chapter newChapter = new Chapter();
        newChapter.setChapterID(chapter.getChapterID());
        newChapter.setChapterName(chapter.getChapterName());
        newChapter.setChapterType(chapter.getChapterType());
        newChapter.setComment(chapter.getComment());
        newChapter.setCourseID(chapter.getCourseID());
        newChapter.setCreater(chapter.getCreater());
        newChapter.setOrders(chapter.getOrders());
        newChapter.setParentChapterID(chapter.getParentChapterID());
        newChapter.setStatus(chapter.getStatus());
        return newChapter;
    }
    //endregion

    //region  验证合法性

    /**
     * 根据appKey，题库id，验证权限.
     *
     * @param appKey     appKey
     * @param itemBankId 题库id
     * @param id         策略id
     * @return the return model
     */

    private ReturnModel basicCheck(String appKey, String itemBankId, String id) {

        //权限验证
        ReturnModel model = check(itemBankId, id);

        if (model.getCode() != GlobalConst.SUCCESS) {
            return model;
        }

        //确认除非非限定appId否则只能修改appId
        if (StringUtils.isEmpty(appKey) || !itemBankService.hasPermission(itemBankId, appKey)) {
            model.setCode(GlobalConst.NO_PERMISSION);
            model.setMessage("无权限操作");
            return model;
        }

        //验证通过返回
        model.setCode(GlobalConst.SUCCESS);
        return model;
    }


    /**
     * 根据题库id,策略id检测题库和策略的合法性
     *
     * @param itemBankId 题库id
     * @param chapterId  章节chapterId
     * @return the return model
     */

    private ReturnModel check(String itemBankId, String chapterId) {
        ReturnModel model = checkItemBank(itemBankId);

        if (model.getCode() != GlobalConst.SUCCESS) {
            return model;
        }

        if (chapterId != null) {
            //Id合法性
            if (StringUtils.isEmpty(chapterId)) {
                model.setCode(GlobalConst.INCOMPLETE_DATA);
                model.setMessage("章节id不合法");
                return model;
            }

            Chapter chapter = mapper.getById(chapterId);
            if (chapter == null) {
                model.setCode(GlobalConst.ID_NOT_EXIST);
                model.setData(null);
                model.setMessage("章节不存在");
                return model;
            }
            //验证通过返回
            model.setData(chapter);
            model.setCode(GlobalConst.SUCCESS);
        }
        return model;
    }

    /**
     * 根据题库id检测题库的合法性
     *
     * @param itemBankId 题库id
     * @return the return model
     */

    private ReturnModel checkItemBank(String itemBankId) {
        ReturnModel model = new ReturnModel();

        //itemBankId合法性
        if (StringUtil.isEmpty(itemBankId)) {
            model.setCode(GlobalConst.INCOMPLETE_DATA);
            model.setMessage("题库id不合法");
            return model;
        }

        //题库合法性
        CourseItemBank itemBank = itemBankService.getCourseItemBankInfo(itemBankId);
        if (itemBank == null) {
            model.setCode(GlobalConst.COURSE_NOT_EXIST);
            model.setMessage("题库id不存在");
            return model;
        }

        //验证通过返回
        model.setCode(GlobalConst.SUCCESS);
        model.setData(itemBank);
        return model;
    }
    //endregion

}
